from app.common.mysql.operate import db
def insert_testcase(param):
    columns = ', '.join(param.keys())  # 获取字典的键作为列名
    placeholders = ', '.join(['%s'] * len(param))  # 生成占位符
    sql = f"INSERT INTO test_case ({columns}) VALUES ({placeholders})"
    
    # 参数元组
    args = tuple(param.values())  # 获取字典的值作为参数
    return db.execute_db(sql, args)


def update_testcase(param):
    sql = """
    UPDATE `test_case` SET name = %s WHERE id = %s
    """
    args = (param['name'], param['id'])
    return db.execute_db(sql, args)

def delete_testcase(param):
    sql = """
    DELETE FROM `test_case` WHERE id = %s
    """
    args = (param['id'])
    return db.execute_db(sql, args)

def select_testcase(param):
    where_clauses = []
    args = []

    for key, value in param.items():
        if isinstance(value, list):  # 处理多个条件
            if all(isinstance(v, tuple) for v in value):  
                # 处理 (operator, val) 形式
                for operator, val in value:
                    where_clauses.append(f"{key} {operator} %s")
                    args.append(val)
            else:
                # 处理 IN 语法
                placeholders = ", ".join(["%s"] * len(value))
                where_clauses.append(f"{key} IN ({placeholders})")
                args.extend(value)
        elif isinstance(value, tuple):  # 处理单个条件
            operator, val = value
            where_clauses.append(f"{key} {operator} %s")
            args.append(val)
        else:  # 默认等于
            where_clauses.append(f"{key} = %s")
            args.append(value)

    where_sql = " AND ".join(where_clauses) if where_clauses else "1"

    sql = f"SELECT * FROM test_case WHERE {where_sql}"
    return db.select_db(sql, args)